package com.cunyme;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


/*
	The main menu currently establishes connections to blackboard and esims, downloading data on classes and cookies.
	Right now, it takes a little time for it to load; not sure if it's ideally efficient, but it's a start.
 */
public class MainMenu extends Activity implements Runnable
{
    ProgressDialog dialog;
    
    Button myBlackboardButton;
    Button myEsimsButton;
    Button myScheduleButton;
    Button myNewsButton;
    Button myForumButton;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainmenu);
        
		dialog = new ProgressDialog(MainMenu.this);

		// make the progress bar cancelable
		dialog.setCancelable(true);
		
		// set a message text
		dialog.setMessage("Loading modules...");
		
		dialog.getWindow().setGravity(Gravity.BOTTOM);
		
		// show it
		dialog.show();
        
		Thread thread = new Thread(MainMenu.this);
		thread.start();
		
        // These are the four buttons and their associated listeners.
        // The code below is straight forward; each click listener
        // simply takes the user to that page.
        myBlackboardButton = (Button)findViewById(R.id.blackboard_button);
        myEsimsButton = (Button)findViewById(R.id.esims_button);
        myScheduleButton = (Button)findViewById(R.id.view_schedule_button);
        myNewsButton = (Button)findViewById(R.id.news_forum_button);
        myForumButton = (Button)findViewById(R.id.forum_button);
        
        myBlackboardButton.setOnClickListener(myBlackboardButtonListener);
        myEsimsButton.setOnClickListener(myEsimsButtonListener);
        myScheduleButton.setOnClickListener(myScheduleButtonListener);
        myNewsButton.setOnClickListener(myNewsButtonListener);
        myForumButton.setOnClickListener(myForumButtonListener);
    }
    
    @Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	public void run()
    {
        // Open up the database again.
        SQLiteDatabase cuny_meDB  = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        helper_functions helpers = new helper_functions();
		Map <String, String> portal_cookies = helpers.getcookies("portal", cuny_meDB);
        
        // Then, we can use the cookies to establish a connection!
		try 
		{
			// We establish a connection
			Connection blackboard_conn = Jsoup.connect("https://bbhosted.cuny.edu/webapps/portal/tab/_1_1/index.jsp").cookie("ObSSOCookie", portal_cookies.get("ObSSOCookie")).cookie("JSESSIONID", portal_cookies.get("JSESSIONID")).cookie("BIGipServerportal_http_pl", portal_cookies.get("BIGipServerportal_http_pl")).cookie("portalErrorCookie", portal_cookies.get("portalErrorCookie")).cookie("ObTEMP", portal_cookies.get("ObTEMP"));
			
			// We store the blackboard page in a Document object
			org.jsoup.nodes.Document blackboard_doc = blackboard_conn.timeout(20*1000).post();
			
			// We store the blackboard cookies in the database,
			// which we'll need for accessing the individual pages of each class
			Map <String, String> blackboard_cookies = blackboard_conn.response().cookies();
	        cuny_meDB.execSQL("INSERT INTO \"cookies_table\" (category, cookies) VALUES (\"blackboard\", \"" + blackboard_cookies + "\");");
			
	        // Again, for the time being, I'm deleting all the old info from the database.  Eventually, we can do
	        // some sort of check to see whether or not we need to insert data.
	        cuny_meDB.execSQL("DELETE FROM \"classes_table\"");
	        
	        // We create a sort of elements array which stores all of the links on the main blackboard page in an array.
	        // We then iterate through them in a for each loop.
	        Elements blackboard_links = blackboard_doc.select("a[href]");
			for (org.jsoup.nodes.Element link : blackboard_links)
	        {
				// The course links are the only ones that start with Spring, Summer, or Fall.  This if statement
				// checks if the name of the link starts with one of those three words.  If it does...
	        	 if (link.text().indexOf("Spring") >= 0 || link.text().indexOf("Summer") >= 0 ||
	        			 link.text().indexOf("Fall") >= 0)
	        	 {
	        		 // ...the link address is parsed, and the course_id is extracted, and inserted into the table.
	        		 String[] course_link_elements = link.attr("abs:href").split("%");
	        		 String course_id = course_link_elements[8];
	        		 course_id = course_id.replace("3d", "");
	        		 
				     cuny_meDB.execSQL("INSERT INTO \"classes_table\" (course_id, course_name) VALUES (\"" + course_id + "\", \"" + link.text() + "\");");
	        	 }
	        }
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			blackboard_failure_handler.sendEmptyMessage(0);
		}
		
		
		// This code connects to esims, and stores the cookies in the database.  It also copies the page to a document object,
		// though I'm not sure if this is necessary.
		try 
		{
			Connection esims_conn = Jsoup.connect("https://esims.cuny.edu/NotLoggedInServlet").data("CurrentCommand", "PortalEntry").cookie("ObSSOCookie", portal_cookies.get("ObSSOCookie")).cookie("JSESSIONID", portal_cookies.get("JSESSIONID")).cookie("BIGipServerportal_http_pl", portal_cookies.get("BIGipServerportal_http_pl")).cookie("portalErrorCookie", portal_cookies.get("portalErrorCookie")).cookie("ObTEMP", portal_cookies.get("ObTEMP"));
			org.jsoup.nodes.Document esims_doc = esims_conn.timeout(40*1000).post();
			Map <String, String> esims_cookies = esims_conn.response().cookies();
	        cuny_meDB.execSQL("INSERT INTO \"cookies_table\" (category, cookies) VALUES (\"esims\", \"" + esims_cookies + "\");");
			success_handler.sendEmptyMessage(0);
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			esims_failure_handler.sendEmptyMessage(0);
		}
        cuny_meDB.close();
    }
    
    
    OnClickListener myBlackboardButtonListener = new OnClickListener()
    {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			
			Intent gotoBlackboard = new Intent(MainMenu.this, Blackboard.class);
			startActivity(gotoBlackboard);
		}
    	
    };
    OnClickListener myEsimsButtonListener = new OnClickListener()
    {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			  Intent gotoEsims = new Intent(MainMenu.this, Esims.class);
			  startActivityForResult(gotoEsims, 0);
		}
    	
    };
    OnClickListener myScheduleButtonListener = new OnClickListener()
    {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			  Intent gotoSchedule = new Intent(MainMenu.this, Schedule.class);
			  startActivity(gotoSchedule);
		}
    	
    };
    OnClickListener myNewsButtonListener = new OnClickListener()
    {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			  Intent gotoNews = new Intent(MainMenu.this, News.class);
			  startActivity(gotoNews);
		}
    	
    };
    OnClickListener myForumButtonListener = new OnClickListener()
    {
		public void onClick(View v) {
			// TODO Auto-generated method stub
			  Intent gotoForum = new Intent(MainMenu.this, Forum.class);
			  startActivity(gotoForum);
		}
    };
    private Handler success_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		dialog.dismiss();
    	}
    };
    private Handler blackboard_failure_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		myBlackboardButton.setEnabled(false);
			Toast.makeText(getApplicationContext(), "Unable to Establish Connection to Blackboard.  Please try again.", Toast.LENGTH_LONG).show();	
    	}
    };
    private Handler esims_failure_handler = new Handler()
    {
    	@Override
    	public void handleMessage(Message msg)
    	{
    		dialog.dismiss();
    		myEsimsButton.setEnabled(false);
    		myScheduleButton.setEnabled(false);
			Toast.makeText(getApplicationContext(), "Unable to Establish Connection to eSims.  Please try again.", Toast.LENGTH_LONG).show();	
    	}
    };
}
